define(['store', 'util', 'aPermissionCard', 'knockout', 'mPrint', 'jquery.print'], function (Store, Util, APermissionCard, ko, MPrint) {
    function ViewModel(params) {
        Util.extend(this, params);

        var scope = this;

        scope.locationHash = '/ArchiveDepartment/ArchiveList';
        //scope.skipOperations = ['addArchive','print'];
        var store = new Store({
            model: 'mArchive',
            id: 'random',
            autoLoad: false,
            fixedQuery: {
                year: params.year,
                classifyCode: params.classifyCode,
                departmentName: params.departmentName,
                keyword: params.keyword
            },
            onInitComplete: function () {
                store.setProxy({url: store.getProxy().originalUrl.formatTpl(params.code)});
                store.load();
                if (!params.codeName) {
                    scope.card.cardBodyTop({
                        name: 'cmp:ArchiveQueryForm',
                        params: {
                            record: store.createModel()
                        }
                    });
                }
            }
        });

        scope.card = {
            title: params.codeName ? params.codeName : '档案列表',
            titleButtons: [],
            cardBodyTop: ko.observable(),
            onOperation: function (operation) {
                Util.ajaxGet({
                    url: Util.getRestUrl('/prints/{0}'.formatTpl(params.code)), data: {
                        year: params.year,
                        classifyCode: params.classifyCode,
                        departmentName: params.departmentName
                    }, callback: function (data) {
                        if (data.success) {
                            ko.root.openModal({
                                title: operation.title,
                                showButtons: false,
                                record: {
                                    bodyCmp: 'cmp:Card',
                                    cardBody: {
                                        name: 'cmp:PrintConfigForm',
                                        params: {
                                            record: new MPrint({archiveIds: data.data}),
                                            onFormButtonClick: function (obj) {
                                                if (obj.record.checkValidity()) {
                                                    var recordJson = obj.record.getFormJsonData();

                                                    if(!recordJson.printAll&&recordJson.archiveIds.length==0){
                                                        Util.showAlert({level:'error',data:'档案号未选择'});

                                                        return
                                                    }

                                                    var ajaxParams = {
                                                        url: Util.getRestUrl('/prints/{0}/basearchives'.formatTpl(params.code)),
                                                        data: {
                                                            ids: recordJson.archiveIds.join(','),
                                                            printAll: recordJson.printAll,
                                                            year: params.year,
                                                            classifyCode: params.classifyCode,
                                                            departmentName: params.departmentName
                                                        },
                                                        callback: function (data) {
                                                            if (data.success) {
                                                                var modalConfig = {
                                                                    title: recordJson.catalog,
                                                                    size: 'lg-1200',
                                                                    showButtons: false,
                                                                    record: {
                                                                        bodyCmp: 'cmp:Card',
                                                                        title: '预览',
                                                                        onOperation: function () {
                                                                            $.print("#printContainer");
                                                                        },
                                                                        titleButtons: [
                                                                            {name: 'print', title: '打印', icon: 'print'}
                                                                        ],
                                                                        cardBody: {
                                                                            name: '',
                                                                            params: {data: data.data,changePage:recordJson.changePage}
                                                                        }
                                                                    }
                                                                };

                                                                switch (recordJson.catalog) {
                                                                    case '档案移交目录（A4横）':
                                                                        modalConfig.record.cardBody.name = 'cmp:PrintArchiveCatalog';
                                                                        break;
                                                                    case '卷内目录（A4纵）':
                                                                        modalConfig.record.cardBody.name = 'cmp:PrintInnerFileCatalog';
                                                                        break;
                                                                    case '案卷封面':
                                                                        modalConfig.record.cardBody.name = 'cmp:PrintArchiveCover';
                                                                        break;
                                                                }

                                                                ko.root.openModal(modalConfig);
                                                            }

                                                        }
                                                    };

                                                    switch (recordJson.catalog) {
                                                        case '卷内目录（A4纵）':
                                                            ajaxParams.data['hasFiles'] = true;
                                                            break;
                                                    }

                                                    Util.ajaxGet(ajaxParams);
                                                }
                                            }
                                        }
                                    },
                                }
                            });
                        }
                    }
                });
                console.log();

            },
            cardBody: {
                name: 'cmp:Grid',
                params: {
                    striped: false,
                    operations: [],
                    store: store,
                    displayFields: ['rowId', 'title', {
                        name: 'classifyNo',
                        columnCmp: 'cmp:Column',
                        formatter:function (data) {
                            var tempValue = '{0}-{1}-{2}'.formatTpl(data.record.year(),data.record.classifyCode(),data.record.volumeNo());

                            if (data.record.fatherId() != 0){
                                tempValue = '{0}.{1}'.formatTpl(tempValue,(data.record.fileNo()/10000).toFixed(4).split('.')[1]);
                            }

                            return tempValue;
                        }
                    }, {name: 'person1', alias: '责任人'}, 'archivedName'],
                    calculateTrCss: function (record) {
                        if (record.fatherId() == 0) {
                            return {'xgx-ams-archive-tr': true};
                        } else {
                            return {}
                        }
                    },
                    operationFilter: function (operations, record) {
                        var addFile = operations.findItemByField({value: 'addFile', name: 'name'});
                        var viewArchive = operations.findItemByField({value: 'viewArchive', name: 'name'});
                        var editArchive = operations.findItemByField({value: 'editArchive', name: 'name'});
                        var deleteArchive = operations.findItemByField({value: 'delete', name: 'name'});
                        var archived = operations.findItemByField({value: 'archived', name: 'name'});
                        var unArchive = operations.findItemByField({value: 'unArchived', name: 'name'});
                        var attachment = operations.findItemByField({value: 'attachment', name: 'name'});
                        var of = [];

                        of.pushItem(viewArchive);

                        if (record.fatherId() == 0) {
                            if (record.archived() == 0) {
                                of.pushItem(addFile);
                                of.pushItem(editArchive);
                                of.pushItem(deleteArchive);
                                of.pushItem(archived);
                            } else {
                                of.pushItem(unArchive);
                            }
                        } else {
                            if (record.archived() == 0) {
                                of.pushItem(editArchive);
                                of.pushItem(deleteArchive);
                            }
                        }

                        of.pushItem(attachment);

                        return of;
                    },
                    onOperation: function (btn, record) {
                        switch (btn.name) {
                            case 'viewArchive':
                                if (record.fatherId() == 0) {
                                    ko.root.openModal({
                                        size: 'lg-1100',
                                        operation: btn.name, record: record, title: '查看档案'
                                    });
                                } else {
                                    ko.root.openModal({
                                        size: 'lg-1100',
                                        operation: 'viewFile', record: record, title: '查看文件'
                                    });
                                }
                                break;
                            case 'addFile':
                                Util.ajaxGet({
                                    url: Util.generateUrl(record.getProxy()) + '/' + record.id() + '/file',
                                    callback: function (data) {
                                        if (data.success) {
                                            data.data.id = 0;

                                            var file = store.createModelFormOBJ(data.data);

                                            ko.root.openModal({
                                                size: 'lg-1100',
                                                operation: btn.name, record: file, title: btn.title,
                                                commit: function (btn, record, callback) {
                                                    file.save(callback);
                                                }
                                            });
                                        }
                                    }
                                });
                                break;
                            case 'editArchive':
                                if (record.fatherId() == 0) {
                                    ko.root.openModal({
                                        size: 'lg-1100',
                                        operation: btn.name, record: record, title: '编辑档案',
                                        commit: function (btn, rec, callback) {
                                            rec.save(function (data) {
                                                if (data.success && ko.storeCache['archiveTree']) ko.storeCache['archiveTree'].load();
                                                callback(data);
                                            });
                                        }
                                    });
                                } else {
                                    ko.root.openModal({
                                        size: 'lg-1100',
                                        operation: 'editFile', record: record, title: '编辑文件',
                                        commit: function (btn, rec, callback) {
                                            rec.save(callback);
                                        }
                                    });
                                }
                                break;
                            case 'archived':
                                ko.root.openModal({
                                    size: 'lg-1100',
                                    operation: btn.name, record: record, title: btn.title,
                                    commit: function (btn, rec, callback) {
                                        rec.processFields();

                                        if (rec.checkValidity()) {
                                            Util.ajaxPost({
                                                url: '{0}/{1}/archived'.formatTpl(Util.generateUrl(record.getProxy()), record.id()),
                                                data: ko.mapping.toJS(rec), callback: function (data) {
                                                    Util.ajaxCallback({
                                                        data: data,
                                                        callback: callback,
                                                        storeId: rec.getStoreId()
                                                    });
                                                }
                                            });
                                        }
                                    }
                                });
                                break;
                            case 'unArchived':
                                ko.root.openModal({
                                    size: 'lg-1100',
                                    operation: btn.name, record: record, title: btn.title,
                                    commit: function (btn, rec, callback) {
                                        Util.ajaxPost({
                                            url: '{0}/{1}/unArchived'.formatTpl(Util.generateUrl(record.getProxy()), record.id()),
                                            callback: function (data) {
                                                Util.ajaxCallback({
                                                    data: data,
                                                    callback: callback,
                                                    storeId: rec.getStoreId()
                                                });
                                            }
                                        });
                                    }
                                });
                                break;
                            case 'attachment':
                                location.hash = '/AttachmentList&{0}'.formatTpl(JSON.js2Uri({
                                    id: record.id(),
                                    code: record.code()
                                }));
                                break;
                        }
                    }
                }
            }
        };

        var print = ko.root.menus.findItemByField({value: 'print', name: 'name'});

        scope.card.titleButtons.pushItem(print);

        this.callParent(params);
    }

    ViewModel.extend(APermissionCard);

    return ViewModel;
});
